package com.inphase.config;

import com.inphase.config.jooq.AutoValueExecuteListener;
import com.inphase.config.jooq.IdVisitListener;
import org.jooq.*;
import org.jooq.conf.Settings;
import org.jooq.impl.DefaultConfiguration;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration;
import org.springframework.boot.autoconfigure.jooq.JooqProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JooqConfiguration {


    @Bean
    AutoValueExecuteListener autoValueExecuteListener(){
        return new AutoValueExecuteListener();
    }

    @Bean
    IdVisitListener idVisitListener(){
        return new IdVisitListener();
    }

    @Bean
    @ConfigurationProperties(prefix = "jooq.setting")
    public Settings settings(){
        return new Settings();
    }

    @Bean
   public DefaultConfiguration defaultConfiguration(JooqProperties properties,
                                                    ConnectionProvider connectionProvider,
                                                    ObjectProvider<TransactionProvider> transactionProvider,
                                                    ObjectProvider<RecordMapperProvider> recordMapperProvider,
                                                    ObjectProvider<Settings> settings,
                                                    ObjectProvider<RecordListenerProvider[]> recordListenerProviders,
                                                    ExecuteListenerProvider[] executeListenerProviders,
                                                    ObjectProvider<VisitListenerProvider[]> visitListenerProviders){
        DefaultConfiguration configuration = new DefaultConfiguration();
        if (properties.getSqlDialect() != null) {
            configuration.set(properties.getSqlDialect());
        }
        configuration.set(connectionProvider);

        configuration.set(transactionProvider.getIfAvailable());

        configuration.set(recordMapperProvider.getIfAvailable());

        configuration.set(settings());
        configuration.set(recordListenerProviders.getIfAvailable());
        configuration.set(executeListenerProviders);
        configuration.set(visitListenerProviders.getIfAvailable());
        configuration.set(autoValueExecuteListener());
        configuration.set(idVisitListener());
        return configuration;
    }
}
